<!-- src/views/login/components/MessageLogin.vue -->
<script setup lang="ts">
import { Field, ErrorMessage } from "vee-validate";
import { toFormValidator } from "@vee-validate/zod";
import * as zod from "zod";
import { AuthAPI } from "@/api/AuthAPI";
import { AxiosError } from "axios";
import useCountdown from "@/logics/useCountdown";
import { useUserStore } from "@/stores/userStore";

// 获取倒计时逻辑
const { start, isActive, count } = useCountdown();
// 获取用于存储用户信息的 store
const userstore = useUserStore();
//创建表单验证规则
const validationSchema = toFormValidator(
  zod.object({
    mobile: zod
      .string({ required_error: "请输入手机号" })
      .regex(/^1[3-9]\d{9}$/, "请输入正确的手机号"),
    code: zod
      .string({ required_error: "请输入验证码" })
      .regex(/^\d{6}$/, "验证码格式错误"),
    isAgree: zod.literal(true, {
      errorMap: () => ({ message: "请勾选同意用户协议" }),
    }),
  })
);
// 创建表单验证对象
const { handleSubmit, setFieldValue, validateField, values } = useForm<{
  mobile: string;
  code: string;
  isAgree: boolean;
}>({
  validationSchema: validationSchema,
});
const onSubmit = handleSubmit((formvalues) => {
  userstore.login(() =>
    AuthAPI.loginByMobileMsgCode(formvalues.mobile, formvalues.code)
  );
});

//获取组件实例化对象
const $ = getCurrentInstance();
//发送验证码事件
async function sendMsgCode() {
  //判断手机号是否正确
  const { valid } = await validateField("mobile");
  //如果手机号不正确
  if (!valid) return;
  //如果正在倒计时停止倒计时
  if (isActive.value) return;
  //捕获错误
  try {
    // 验证通过 发送手机验证码
    await AuthAPI.sendMsgCodeOfMobileLogin(values.mobile);
    //倒计时
    start(60);
    // 消息提示
    $?.proxy?.$message({ type: "success", msg: "手机验证码发送成功" });
  } catch (e) {
    if (e instanceof AxiosError) {
      //消息提示
      $?.proxy?.$message({ type: "error", msg: e.response?.data.message });
    } else {
      // 消息提示
      $?.proxy?.$message({ type: "error", msg: "手机验证码发送失败" });
    }
  }
}
</script>
<template>
  <form @submit="onSubmit">
    <Field as="div" name="mobile" class="form-item" v-slot="{ field }">
      <div class="input">
        <i class="iconfont icon-user"></i>
        <input v-bind="field" type="text" placeholder="请输入手机号" />
      </div>
      <ErrorMessage as="div" class="error" name="mobile" v-slot="{ message }">
        <i class="iconfont icon-warning"></i>{{ message }}
      </ErrorMessage>
    </Field>
    <Field as="div" name="code" class="form-item" v-slot="{ field }">
      <div class="input">
        <i class="iconfont icon-code"></i>
        <input v-bind="field" type="password" placeholder="请输入验证码" />
        <span class="code" @click="sendMsgCode">{{
          isActive ? `剩余${count}秒` : "发送验证码"
        }}</span>
      </div>
      <ErrorMessage as="div" name="code" class="error" v-slot="{ message }">
        <i class="iconfont icon-warning"></i>{{ message }}
      </ErrorMessage>
    </Field>
    <Field as="div" name="isAgree" class="form-item" v-slot="{ field }">
      <div class="agree">
        <XtxCheckbox
          :checked="values.isAgree"
          @onChanged="
            setFieldValue('isAgree', $event);
            validateField('isAgree');
          "
        />
        <span>我已同意</span>
        <a href="javascript:">《隐私条款》</a>
        <span>和</span>
        <a href="javascript:">《服务条款》</a>
      </div>
      <ErrorMessage as="div" name="isAgree" class="error" v-slot="{ message }">
        <i class="iconfont icon-warning"></i>{{ message }}
      </ErrorMessage>
    </Field>
    <button type="submit" class="btn">登录</button>
  </form>
</template>
